package com.sunxiansheng.redis.init;

import com.sunxiansheng.redis.util.SpringContextUtil;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Description: 项目启动时进行缓存预热
 * @Author sun
 * @Create 2024/7/19 12:28
 * @Version 1.0
 */
@Component
public class InitCache implements CommandLineRunner {

    /**
     * 项目启动时会执行
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        System.out.println("项目启动！");
        // 获取Spring上下文
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        // 根据缓存预热抽象类的类型，来获取所有子类的bean，并放到map中
        Map<String, AbsCache> beanMap = applicationContext.getBeansOfType(AbsCache.class);
        if (beanMap.isEmpty()) {
            return;
        }
        // 遍历所有的AbsCache子类，调用init方法
        for (Map.Entry<String, AbsCache> entry : beanMap.entrySet()) {
            AbsCache absCache = entry.getValue();
            absCache.initCache();
        }
    }
}